package com.blacktry.config.schedule;

import com.blacktry.service.JobService;
import com.blacktry.utils.GetBeanUtil;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.stereotype.Component;

/**
 * @calssName MyJobListener
 * @Description 定时任务监听器:通过监听的方式记录 记录定时任务的执行记录
 * @Author blackTry
 */
@Component
public
class MyJobListener implements JobListener {
    private JobService jobService;

    // 用于保存 logId
    ThreadLocal<String> threadLocal = new ThreadLocal<>();

    @Override
    public String getName() {
        return "myJobListener";
    }

    // 执行开始新增一条执行日志，状态为执行中
    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
        if(jobService == null){
            jobService = GetBeanUtil.getBean(JobService.class);
        }
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        String name = jobDetail.getKey().getName();
        Integer logId = jobService.saveScheduleLog(name, 1, "");
        threadLocal.set(String.valueOf(logId)); // 把执行记录放到 threadLocal,提供给执行结束后取此结果
    }

    // 任务拒绝执行时，修改日志状态为：执行失败
    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
        String logId = threadLocal.get(); // 执行记录logId
        jobService.updateScheduleLog(logId, -1, "执行失败");
    }

    // 任务执行时结果，判断是否有异常，修改对应状态
    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) {
        String logId = threadLocal.get(); // 执行记录logId
        if(e == null){ // 没有异常修改记录为成功
            jobService.updateScheduleLog(logId, 200, "执行成功");
        }else{ // 存在异常修改记录失败，并且把异常信息保存到数据库中
            jobService.updateScheduleLog(logId, -1, e.toString());
        }
    }
}